import request from '@/utils/request'
import axios from 'axios'

// 获取文档列表
export function getDocuments() {
  return request({
    url: '/api/documents',
    method: 'get'
  })
}

// 上传文档
export function uploadDocument(file, options = {}) {
  const formData = new FormData()
  formData.append('file', file)
  
  if (options.title) {
    formData.append('title', options.title)
  }
  
  return request({
    url: '/api/documents/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 向量化文档 - 使用 SSE 处理进度
export function vectorizeDocument(id, onProgress) {
  return new Promise((resolve, reject) => {
    const eventSource = new EventSource(`/api/documents/${id}/vectorize`)

    let hasError = false
    let isCompleted = false

    // 连接打开时的处理
    eventSource.onopen = () => {
      console.log('SSE connection opened for vectorization')
    }

    // 消息处理
    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('SSE message:', data)
        
        // 调用进度回调
        if (typeof onProgress === 'function') {
          onProgress(data)
        }
        
        if (data.status === 'completed') {
          isCompleted = true
          eventSource.close()
          resolve(data)
        } else if (data.status === 'error') {
          hasError = true
          eventSource.close()
          reject(new Error(data.message))
        }
      } catch (error) {
        console.error('Failed to parse SSE message:', error)
        hasError = true
        eventSource.close()
        reject(error)
      }
    }

    // 错误处理
    eventSource.onerror = (error) => {
      console.error('SSE connection error:', error)
      if (!hasError && !isCompleted) {
        hasError = true
        eventSource.close()
        reject(new Error('向量化处理连接失败'))
      }
    }
  })
}

// 获取文档内容
export function getDocumentContent(id) {
  return request({
    url: `/api/documents/${id}/content`,
    method: 'get'
  })
}

// 删除文档
export function deleteDocument(id) {
  return request({
    url: `/api/documents/${id}`,
    method: 'delete'
  })
}

// 获取向量化内容
export function getVectorizedContent(id, params = {}) {
  return request({
    url: `/api/documents/${id}/vectorized`,
    method: 'get',
    params: {
      page: params.page || 1,
      pageSize: params.pageSize || 10
    }
  })
}

// 删除向量化内容
export function deleteVectorizedContent(id) {
  return request({
    url: `/api/documents/${id}/vectorized`,
    method: 'delete'
  })
}

// 预览文档分段
export function previewDocumentChunks(id, params = {}) {
  return request({
    url: `/api/documents/${id}/preview-chunks`,
    method: 'post',
    data: params
  })
} 